package com.fengxu.springcloud.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

@RestController
public class FlowLimitController {

    @GetMapping("/testA")
    public String testA() {
        System.out.println("调用了一次A");
        return "---------------A";
    }


    @GetMapping("/testB")
    public String testB(){
        testA();
        return "---------------B";
    }

    @GetMapping("/testC")
    public String testC(){
        try {
            TimeUnit.SECONDS.sleep(1);
            System.out.println("调用了testc方法...");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "---------------C";
    }

    @GetMapping("/testD")
    public String testD(){
        System.out.println("调用了testd方法... 测试异常比例！");
        int a = 1 / 0;
        return "---------------C";
    }

    @GetMapping("/testHotkey")
    // @SentinelResource 类似于hystrix的@HystrixCommand
    // value表示标识该资源的资源名
    // blockHandler设置当该请求不符合sentinel设置的热点规则时触发的方法！
    @SentinelResource(value = "testHotkey", blockHandler = "limitHotKey")
    public String testHotKey(String p1,String p2){

        return "---------------testHotKey";
    }

    // 该方法是testHotKey的兜底方法, 必须添加BlockException方法参数
    public String limitHotKey(String p1, String p2, BlockException e){

        System.out.println(e);
        // sentinel的默认提示为:Blocked by Sentinel (flow limiting)
        return "---------------limitHotKey ：cause -> ";
    }

}
